import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn, VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SystemUserApi } from '#/api';

import { $t } from '#/locales';
import { z } from '#/adapter/form';
import { computed, type Ref } from 'vue';
import dayjs from 'dayjs';
import { uploadFile } from '#/api';

export function useFormSchema(roleOptionsRef: Ref<{ label: string; value: string }[]>): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'username',
      label: $t('system.user.username'),
      rules: 'required',
    },
    {
      component: 'Upload',
      componentProps: {
        // 更多属性见：https://ant.design/components/upload-cn
        accept: '.png,.jpg,.jpeg,.webp',
        // 自动携带认证信息
        customRequest: upload_file,
        disabled: false,
        maxCount: 1,
        multiple: false,
        showUploadList: true,
        // 上传列表的内建样式，支持四种基本样式 text, picture, picture-card 和 picture-circle
        listType: 'picture-card',
      },
      fieldName: 'avatar',
      label: $t('system.user.avatar'),
      renderComponentContent: () => {
        return {
          // default: () => $t('examples.form.upload-image'),
          default: () => '点击上传图片',
        };
      },
      rules: 'required',
      help: '支持jpg/png格式，最大2M', // 帮助信息
    },
    {
      component: 'Input',
      fieldName: 'realName',
      label: $t('system.user.realName'),
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'email',
      label: $t('system.user.email'),
      rules: z.string().min(1, '请输入邮箱').email('请输入正确的邮箱'),
    },
    {
      component: 'Input',
      fieldName: 'phone',
      label: $t('system.user.phone'),
    },
    {
      component: 'RadioGroup',
      componentProps: {
        buttonStyle: 'solid',
        options: [
          { label: $t('common.enabled'), value: 1 },
          { label: $t('common.disabled'), value: 0 },
        ],
        optionType: 'button',
      },
      defaultValue: 1,
      fieldName: 'status',
      label: $t('system.user.status'),
    },
    {
      component: 'Input',
      fieldName: 'remark',
      label: $t('system.user.remark'),
    },
    {
      component: 'CheckboxGroup',
      fieldName: 'roles',
      label: $t('system.user.role'),
      componentProps: {
        options: computed(() => {
          return roleOptionsRef.value;
        }),
      },
      rules: 'required',
    },
  ];
}

/**
 * 文件上传
 * */ 
async function upload_file(options: any) {
  try {
    console.log("options",options)
    const uploadUserId = localStorage.getItem("updateUserInfoById")
    console.log("当前用户updateUserId:", uploadUserId);
    if (!uploadUserId) {
      throw new Error("未获取到当前用户ID");
    }
    const res = await uploadFile(options.file, uploadUserId); // res就是后端data
    let url = '';
    if (typeof res === 'string') {
      url = res;
    } else if (typeof res === 'object') {
      url = res.uploadUrl || res.url || '';
    }
    if (!url) {
      throw new Error('未获取到图片上传地址');
    }
    options.onSuccess({ url }, options.file);
    localStorage.removeItem("updateUserInfoById");
  } catch (e) {
    console.error('文件上传失败:', e);
    options.onError(e);
  }
}

export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'username',
      label: $t('system.user.username'),
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: [
          { label: $t('common.enabled'), value: 1 },
          { label: $t('common.disabled'), value: 0 },
        ],
      },
      fieldName: 'status',
      label: $t('system.user.status'),
    },
    {
      component: 'Input',
      fieldName: 'email',
      label: $t('system.user.email'),
    },
  ];
}

export function useColumns<T = SystemUserApi.SystemUser>(
  onActionClick: OnActionClickFn<T>,
  onStatusChange?: (newStatus: any, row: T) => PromiseLike<boolean | undefined>,
): VxeTableGridOptions['columns'] {
  return [
    {
      field: 'username',
      title: $t('system.user.username'),
      width: 200,
    },
    {
      field: 'avatar',
      title: $t('system.user.avatar'),
      width: 50,
      cellRender: { name: 'CellImage' }, // 使用自定义渲染器: 展示图片
    },
    {
      field: 'email',
      title: $t('system.user.email'),
      width: 200,
    },
    {
      field: 'phone',
      title: $t('system.user.phone'),
      width: 150,
    },
    {
      field: 'roles',
      title: $t('system.user.role'),
      width: 180,
    },
    {
      cellRender: {
        attrs: { beforeChange: onStatusChange },
        name: onStatusChange ? 'CellSwitch' : 'CellTag',
      },
      field: 'status',
      title: $t('system.user.status'),
      width: 100,
    },
    {
      field: 'remark',
      minWidth: 100,
      title: $t('system.user.remark'),
    },
    {
      field: 'createTime',
      title: $t('system.user.createTime'),
      width: 200,
      formatter: ({ cellValue }) => cellValue ? dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss') : '',
    },
    {
      align: 'center',
      cellRender: {
        attrs: {
          nameField: 'username',
          nameTitle: $t('system.user.username'),
          onClick: onActionClick,
        },
        name: 'CellOperation',
      },
      field: 'operation',
      fixed: 'right',
      title: $t('system.user.operation'),
      width: 130,
    },
  ];
}
